package com.ncmmall.api.apis.mall;


import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.ncmmall.api.apis.service.Result;
import com.ncmmall.api.params.DataDTO;
import com.ncmmall.api.params.SkuDTO;
import com.ncmmall.api.security.Securitys;
import com.ncmmall.application.business.goods.GoodsApplication;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.goods.QGoods;
import com.ncmmall.domain.business.goods.sku.GoodsSku;
import com.ncmmall.domain.business.merchant.banner.MerchantBanner;
import com.ncmmall.domain.business.merchant.banner.QMerchantBanner;
import com.ncmmall.domain.security.user.QWebUser;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author linxs
 * 门店
 */
@RestController
@RequestMapping(value = "/shop")
@Component
public class ShopApi {

    private Logger logger = LoggerFactory.getLogger(ShopApi.class);

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private GoodsApplication goodsApplication;

    @Value("${store.domain}")
    private String storeDomain;

    /**
     * 采购端我的个人中心-我的店铺
     *
     * @param request
     * @param id
     * @return
     */
    @RequestMapping(value = "/my", method = RequestMethod.GET)
    @ResponseBody
    public Result my(HttpServletRequest request) {
        Result result = new Result();
        try {

            WebUser merchant = Securitys.user(request);

            Map<String, Object> data = Maps.newHashMap();
            data.put("id", merchant.getId());
            data.put("name", merchant.getShopName());
            data.put("shopBanner", storeDomain + "/uploads/" + merchant.getShopBanner());
            data.put("logo", storeDomain + "/avatar/" + merchant.getAvatar());

            return result.ok().inject(data);

        } catch (IllegalArgumentException e) {

            return result.fail().setMsg(e.getMessage());

        } catch (Exception e) {

            logger.error("[获取商品详情异常]", e);
            return result.fail().setMsg("网络连接失败");
        }

    }

    /**
     * 商品上架
     *
     * @param request
     * @param params
     * @return
     */
    @RequestMapping(value = "/goods/publish", method = RequestMethod.PUT)
    @ResponseBody
    public Result publish(HttpServletRequest request, @RequestBody DataDTO params) {
        Result result = new Result();
        try {
            WebUser member = Securitys.user(request);
            Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(params.getId()), Goods.class);

            goodsApplication.applyPutaway(goods);

            return result.ok();

        } catch (Exception e) {
            logger.error("[确认收货异常]", e);
            return result.fail().setMsg("确认收货异常");
        }
    }

    /**
     * 商品下架
     *
     * @param request
     * @param params
     * @return
     */
    @RequestMapping(value = "/goods/soldout", method = RequestMethod.PUT)
    @ResponseBody
    public Result soldout(HttpServletRequest request, @RequestBody DataDTO params) {
        Result result = new Result();
        try {
            WebUser member = Securitys.user(request);
            Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(params.getId()), Goods.class);

            goodsApplication.soldout(goods);

            return result.ok();

        } catch (Exception e) {
            logger.error("[确认收货异常]", e);
            return result.fail().setMsg("确认收货异常");
        }
    }

    /**
     * 编辑商品
     *
     * @param request
     * @param params
     * @return
     */
    @RequestMapping(value = "/goods/modify", method = RequestMethod.PUT)
    @ResponseBody
    public Result modify(HttpServletRequest request, @RequestBody List<SkuDTO> params) {
        Result result = new Result();
        try {
            WebUser member = Securitys.user(request);

            List<GoodsSku> skus = Lists.newArrayList();

            for (SkuDTO param : params) {
                GoodsSku sku = new GoodsSku();
                BeanUtils.copyProperties(param, sku);
                skus.add(sku);
            }

            goodsApplication.modifyStore(skus);

            return result.ok();

        } catch (Exception e) {
            logger.error("[确认收货异常]", e);
            return result.fail().setMsg("确认收货异常");
        }
    }

    /**
     * 编辑一键代发商品
     *
     * @param request
     * @param params
     * @return
     */
    @RequestMapping(value = "/goods/modifyIssuing", method = RequestMethod.PUT)
    @ResponseBody
    public Result modifyIssuing(HttpServletRequest request, @RequestBody List<SkuDTO> params) {
        Result result = new Result();
        try {
            WebUser member = Securitys.user(request);

            List<GoodsSku> skus = Lists.newArrayList();

            for (SkuDTO param : params) {
                GoodsSku sku = new GoodsSku();
                BeanUtils.copyProperties(param, sku);
                skus.add(sku);
            }

            goodsApplication.modifyIssuing(skus);

            return result.ok();

        } catch (Exception e) {
            logger.error("[确认收货异常]", e);
            return result.fail().setMsg("确认收货异常");
        }
    }

    /**
     * 采购端我的个人中心-我的店铺-商品列表
     *
     * @param request
     * @param pageNo
     * @param pageSize
     * @param status
     * @return
     */
    @RequestMapping(value = "/goods/list", method = RequestMethod.GET)
    @ResponseBody
    public Result list(HttpServletRequest request, @RequestParam(defaultValue = "1") int pageNo, @RequestParam(defaultValue = "20") int pageSize, @RequestParam(defaultValue = "1") int status) {
        Result result = new Result();
        try {

            QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageNo).setPageSize(pageSize);

            String hql = "";

            if (status == 1) {
                hql = "select g from Goods g where g.status = 3 and g.merchant.id = :id order by g.createTime desc ";
            } else {
                hql = "select g from Goods g where g.status = 5 and g.merchant.id = :id order by g.createTime desc ";
            }

            Map<String, Object> map = new HashMap<>();
            map.put("id", Securitys.user(request).getId());

            QueryPage<Goods> page = queryChannelService.findPage(hql, pageRequest.setParams(map), Goods.class);
            for (Goods goods : page.getResult()) {
                goods.setDefaultImage(storeDomain + "/uploads/" + goods.getDefaultImage());

                List<GoodsSku> skus = goods.getSkus();
                for (GoodsSku sku : skus) {
                    sku.setSkuNames(StringUtils.replace(sku.getSkuNames(), ",", " "));
                }
                goods.setSkus(skus);
            }


            return result.ok().inject(page);

        } catch (Exception e) {

            logger.error("[分类商品列表获取数据异常]", e);
            return result.fail().setMsg("网络连接失败");
        }

    }

    /**
     * 店铺信息
     */
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public Result info(Long id) {
        Result result = new Result();
        try {

            Assert.notNull(id, "id不能为空");

            WebUser merchant = queryChannelService.findOne(QWebUser.webUser.id.eq(id).and(QWebUser.webUser.role.name.eq("SUPPLIER")), WebUser.class);
            Assert.notNull(merchant, "店铺不存在");

            Map<String, Object> data = new HashMap<>();
            data.put("name", merchant.getShopName());
            data.put("shopBanner", storeDomain + "/uploads/" + merchant.getShopBanner());
            data.put("logo", storeDomain + "/avatar/" + merchant.getAvatar());
            data.put("telephone", merchant.getMobile());

            List<MerchantBanner> banners = queryChannelService.findAll(QMerchantBanner.merchantBanner.merchant.id.eq(merchant.getId())
                    .and(QMerchantBanner.merchantBanner.status.eq(2)), MerchantBanner.class);
            for (MerchantBanner banner : banners) {
                if (StrUtil.isNotBlank(banner.getImage())) {
                    banner.setImage(storeDomain + "/uploads/" + banner.getImage());
                }
            }
            data.put("banners", banners);
            data.put("channels", queryChannelService.selectAllMap("select * from mall_goods_channel where deleteStatus = 0 and id in (select channel_id from mall_merchant_goods_channel where merchant_id = :id )", ImmutableMap.of("id", merchant.getId())));
            return result.ok().inject(data);
        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("[获取商品详情异常]", e);
            return result.fail().setMsg("网络连接失败");
        }
    }


    /**
     * 店铺商品
     *
     * @param shopId
     * @param orderType
     * @param orderMethod
     * @param channelId
     * @param pageNo
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/goodsList", method = RequestMethod.GET)
    @ResponseBody
    public Result goodsList(@RequestParam(defaultValue = "0") long shopId, @RequestParam(defaultValue = "0") int orderType, @RequestParam(defaultValue = "0") int orderMethod, @RequestParam(defaultValue = "0") long channelId, @RequestParam(defaultValue = "1") int pageNo, @RequestParam(defaultValue = "20") int pageSize) {
        Result result = new Result();
        try {

            QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageNo).setPageSize(pageSize);

            String hql = "select g from Goods g where g.status = 3 and g.merchant.id = :id ";
            Map<String, Object> map = new HashMap<>();
            map.put("id", shopId);

            hql = builderSQL(orderType, orderMethod, channelId, map, hql);

            QueryPage<Goods> page = queryChannelService.findPage(hql, pageRequest.setParams(map), Goods.class);
            for (Goods goods : page.getResult()) {
                goods.setDefaultImage(storeDomain + "/uploads/" + goods.getDefaultImage());
            }

            return result.ok().inject(page);

        } catch (Exception e) {

            logger.error("[分类商品列表获取数据异常]", e);
            return result.fail().setMsg("网络连接失败");
        }

    }

    private String builderSQL(int orderType, int orderMethod, long channelId, Map<String, Object> map, String hql) {

        if (channelId > 0) {
            hql += " and g.goodsChannel.parent.parent.id = :cid ";
            map.put("cid", channelId);
        }

        //按价格排序
        if (orderType == 1) {

            if (orderMethod == 0) {
                hql += " order by g.defaultPrice ";
            }
            if (orderMethod == 1) {
                hql += " order by g.defaultPrice desc ";
            }
            if (orderMethod == 2) {
                hql += " order by g.defaultPrice asc ";
            }

        }

        if (orderType == 2) {

            if (orderMethod == 0) {
                hql += " order by g.salesVolume ";
            }
            if (orderMethod == 1) {
                hql += " order by g.salesVolume desc ";
            }
            if (orderMethod == 2) {
                hql += " order by g.salesVolume asc ";
            }

        }


        return hql;
    }


}
